import {
  Card,
  Form,
  Tag,
  Button,
  Row,
  Col,
  Select,
  Space,
  message,
  InputNumber,
  Checkbox,
} from 'antd';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import React, { FC, useEffect, useState } from 'react';
import { permuteUnique } from '@/utils/utils';
import _ from 'lodash';
import { attrAllRule, createValRule } from '../service';

const { Option } = Select;

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 4 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 20 },
  },
};
const formItemLayoutWithOutLabel = {
  wrapperCol: {
    xs: { span: 24, offset: 0 },
    sm: { span: 20, offset: 4 },
  },
};

interface AdvancedFormProps {}

interface stateData {
  attrList: any;
  current: Object;
}

const handlePer = (curent: object) => {
  const ansIds: any = [];
  const ansNames: any = [];
  Object.values(curent).forEach((it) => {
    if (it.attr_vals) {
      ansIds.push(it.attr_vals.filter((item: any) => item.checked).map((val: any) => val.id));
      ansNames.push(it.attr_vals.filter((item: any) => item.checked).map((val: any) => val.name));
    }
  });
  return [ansIds, ansNames];
};

const Attr: FC<AdvancedFormProps> = (props: any) => {
  const [form] = Form.useForm();
  const [state, setState] = useState<stateData>({
    attrList: [],
    current: {},
  });

  const { attrList, current } = state;

  // 商品规格
  const AttrValRender = () => {
    const {
      match: {
        params: { id },
      },
      detail,
    } = props;
    const { goods_skus = [] } = detail;
    const onFinish = async (values: any) => {
      const { attr_val } = values;
      const list = attr_val.map((it: any) => {
        const item = attrList.find((attr: any) => attr.id === it.attr_id);
        const { name: attr_name, attr_vals } = item;
        return {
          ...it,
          vals: attr_vals.filter((f: any) => f.checked),
          attr_name,
        };
      });
      Object.assign(values, { attr_val: list });
      const { code } = await createValRule(id, values);
      if (code === 0) {
        message.success('新增成功');
      }
    };
    const [perList, perNamesList] = handlePer(current);
    const perArray = permuteUnique(perList);
    const perValArray = permuteUnique(perNamesList);
    const values = perArray.map((it: any, index: number) => {
      const currentSku = goods_skus.find((sku: any) => sku.composeIds === it) || {};
      return {
        composeIds: it,
        composeNames: perValArray[index],
        stock: currentSku.stock,
        price: currentSku.price,
      };
    });

    form.setFieldsValue({ goods_attr: values });
    return (
      <Form form={form} name="dynamic_form_nest_item" onFinish={onFinish} autoComplete="off">
        <Form.List name="goods_attr">
          {(fields) => {
            return (
              <div>
                {fields.map((field) => (
                  <>
                    <Space
                      key={field.key}
                      style={{ display: 'flex', marginBottom: 8 }}
                      align="start"
                    >
                      <Form.Item>
                        {values[field.key].composeNames.split(',').map((it: any) => (
                          <Tag color="orange">{it}</Tag>
                        ))}
                      </Form.Item>
                      <Form.Item
                        {...field}
                        label="库存"
                        name={[field.name, 'stock']}
                        fieldKey={[field.fieldKey, 'stock']}
                        style={{ width: 130 }}
                      >
                        <InputNumber placeholder="请输入库存" min={1} />
                      </Form.Item>
                      <Form.Item
                        {...field}
                        label="价格"
                        name={[field.name, 'price']}
                        fieldKey={[field.fieldKey, 'price']}
                        style={{ width: 130 }}
                      >
                        <InputNumber min={0} />
                      </Form.Item>
                    </Space>
                  </>
                ))}
              </div>
            );
          }}
        </Form.List>

        <Form.Item>
          <Button type="primary" htmlType="submit">
            提交
          </Button>
        </Form.Item>
      </Form>
    );
  };

  const AttrRender = () => {
    const onFinish = (values: any) => {
      console.log('Received values of form:', values);
    };

    const onChange = (checkedValues: any, index: number) => {
      const {
        target: { checked, value },
      } = checkedValues;
      const attr_index = current[index].attr_vals.findIndex((it: any) => it.id === value);
      _.set(current, `[${index}].attr_vals.[${attr_index}].checked`, checked);
      setState({
        ...state,
        current,
      });
    };

    return (
      <Form
        form={form}
        name="dynamic_form_item"
        {...formItemLayoutWithOutLabel}
        onFinish={onFinish}
      >
        <Form.List name="attr_val">
          {(fields, { add, remove }) => {
            return (
              <div>
                {fields.map((field, index) => (
                  <>
                    <Form.Item
                      {...(index === 0 ? formItemLayout : formItemLayoutWithOutLabel)}
                      label={index === 0 ? '属性值' : ''}
                      required={false}
                      key={field.key}
                    >
                      <Form.Item
                        {...field}
                        noStyle
                        name={[field.name, 'attr_id']}
                        fieldKey={[field.fieldKey, 'attr_id']}
                      >
                        <Select
                          style={{ width: '60%' }}
                          placeholder="请选择商品属性"
                          onChange={(val) => {
                            current[field.key] = attrList.find((it: any) => it.id === val);
                            setState({
                              ...state,
                              current,
                            });
                          }}
                        >
                          {attrList.map((it: any) => (
                            <Option value={it.id} key={it.id}>
                              {it.name}
                            </Option>
                          ))}
                        </Select>
                      </Form.Item>
                      {fields.length > 1 ? (
                        <MinusCircleOutlined
                          className="dynamic-delete-button"
                          style={{ margin: '0 8px' }}
                          onClick={() => {
                            remove(field.name);
                          }}
                        />
                      ) : null}
                    </Form.Item>
                    <Form.Item>
                      <Checkbox.Group
                        style={{ width: '100%' }}
                        value={current[field.key]?.attr_vals
                          .filter((it: any) => it.checked)
                          .map((it: any) => it.id)}
                      >
                        <Row>
                          {current[field.key]?.attr_vals.map((it: any) => (
                            <Col span={4}>
                              <Checkbox value={it.id} onChange={(v: any) => onChange(v, index)}>
                                {it.name}
                              </Checkbox>
                            </Col>
                          ))}
                        </Row>
                      </Checkbox.Group>
                      ,
                    </Form.Item>
                  </>
                ))}

                <Form.Item>
                  <Button
                    type="dashed"
                    onClick={() => {
                      add();
                    }}
                    style={{ width: '60%' }}
                  >
                    <PlusOutlined />
                    新增
                  </Button>
                </Form.Item>
              </div>
            );
          }}
        </Form.List>
      </Form>
    );
  };

  const loadData = async () => {
    const { data, code } = await attrAllRule();
    if (code === 0) {
      setState({
        ...state,
        attrList: data,
      });
    }
  };

  const loadGoodsSku = async () => {
    const { detail } = props;
    const { goods_attrs = [] } = detail;
    const attr_val = goods_attrs.map((item: any, key: number) => {
      const { attr_id, goods_attr_vals = [] } = item;
      const attr_key_ids = goods_attr_vals.map((val: any) => val.attr_key_id);
      if (attrList.length) {
        current[key] = attrList.find((it: any) => it.id === attr_id);
        current[key].attr_vals.forEach((attr: any, value: number) => {
          if (attr_key_ids.includes(attr.id)) {
            _.set(current, `[${key}].attr_vals.[${value}].checked`, true);
          }
        });
      }
      return {
        attr_id,
      };
    });
    if (Object.keys(current).length) {
      setState({
        ...state,
        current,
      });
    }

    form.setFieldsValue({ attr_val });
  };

  // 回显商品属性
  useEffect(() => {
    loadGoodsSku();
  }, [attrList]);

  useEffect(() => {
    loadData();
  }, []);

  return (
    <Row>
      <Col span={12}>
        <Card title="商品属性" bordered={false}>
          {AttrRender()}
        </Card>
      </Col>
      <Col span={24}>
        <Card title="商品规格" bordered={false}>
          {AttrValRender()}
        </Card>
      </Col>
    </Row>
  );
};

export default Attr;
